package com.zengdada.authority.config;

import com.alibaba.fastjson.JSONObject;
import com.zengdada.authority.config.quartz.JobAndTriggerManager;
import com.zengdada.authority.model.TimedTask;
import com.zengdada.authority.model.TimedTaskCron;
import com.zengdada.authority.model.TimedTaskExtend;
import com.zengdada.authority.service.TimedTaskAuthorityService;
import com.zengdada.authority.service.TimedTaskCronAuthorityService;
import com.zengdada.authority.utils.where.Where;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Trigger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author 12614
 * @contact 1261438511@qq.com
 * @date 2019-03-29 16:26
 */
//被spring容器管理
@Component
@Order(1)
@Slf4j
public class AuthorityApplicationRunner implements ApplicationRunner {

    @Autowired
    JobAndTriggerManager jobAndTriggerManager;

    @Autowired
    @Qualifier("timedTaskAuthorityServiceImpl")
    TimedTaskAuthorityService timedTaskAuthorityService;
    @Autowired
    @Qualifier("timedTaskCronAuthorityServiceImpl")
    TimedTaskCronAuthorityService timedTaskCronAuthorityService;

    @Value("${project.runner.start.job:true}")
    Boolean startJob;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 修改异常状态的任务 (暂停、正常（启动）、停止)
        List<TimedTask> abnormalList = timedTaskAuthorityService.selectPageInfoByParam(new Where("taskState", Where.Formula.NOT_IN, "NONE,PAUSED,NORMAL"), null, null).getList();
        if (abnormalList.size() > 0) {
            abnormalList.forEach(e -> timedTaskAuthorityService.updateById(new TimedTask() {{
                setId(e.getId());
                setTaskState(Trigger.TriggerState.NONE.name());
            }}));
        }
        //是否启动默认任务
        if (startJob) {
            List<Where> params = new ArrayList<>();
            params.add(new Where("state", "1", Where.FieldType.INTEGER));
            params.add(new Where("taskState", Where.Formula.IN, "PAUSED,NORMAL"));
            List<TimedTask> list = timedTaskAuthorityService.selectPageInfoByParam(new Where(Where.Formula.OR, params), null, null).getList();
            if (list.size() != 0) {
                List<TimedTaskCron> crons = timedTaskCronAuthorityService.selectPageInfoByParam(new Where("id", Where.Formula.IN, list.stream().map(TimedTask::getCronId).collect(Collectors.joining(","))), null, null).getList();
                for (TimedTask timedTask : list) {
                    TimedTaskExtend timedTaskExtend = JSONObject.parseObject(JSONObject.toJSONString(timedTask), TimedTaskExtend.class);
                    Optional<TimedTaskCron> optional = crons.stream().filter(i -> i.getId().equals(timedTask.getCronId())).findFirst();
                    if (optional.isPresent()) {
                        timedTaskAuthorityService.addJob(timedTaskExtend, optional.get());
                        if (Trigger.TriggerState.PAUSED.name().equals(timedTask.getTaskState())) {
                            timedTaskAuthorityService.changeTaskState(timedTask.getId(), "pause");
                        }
                    }
                }
            }
        }
    }
}
